/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Consulta.java
 *
 * Created on Dec 21, 2011, 5:58:25 PM
 */
package Interfaces;

import Consulta.DB;
import java.io.IOException;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import Imprimibles.Padre;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPTable;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JTextField;

/**
 *
 * @author carlostejada
 */
public class Consulta extends javax.swing.JFrame {

    /** Creates new form Consulta */
    public Consulta() {
        initComponents();
        setNombreAlmacen();
        setNombreMaterial();
        submit.setEnabled(false);
        comprobarDatos cD = new comprobarDatos(codigo, nombreMaterial, almacen, submit);
        cD.start();
    }

    private void setNombreAlmacen() {
        manejadorDB mDB = new manejadorDB();
        almacen.addItem("");
        for (Map.Entry<Integer, String> respuestaEntry : mDB.getNombreAlmacen().entrySet()) {
            almacen.addItem(respuestaEntry.getKey() + "-" + respuestaEntry.getValue());
        }
    }

    private void setNombreMaterial() {
        manejadorDB db = new manejadorDB();
        nombreMaterial.addItem("");
        for (String s : db.getNombreMateriales()) {
            nombreMaterial.addItem(s);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        nombreMaterial = new javax.swing.JComboBox();
        codigo = new javax.swing.JTextField();
        almacen = new javax.swing.JComboBox();
        submit = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        nombreMaterial.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nombreMaterialActionPerformed(evt);
            }
        });

        codigo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                codigoFocusLost(evt);
            }
        });

        submit.setText("Generar Reporte");
        submit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitActionPerformed(evt);
            }
        });

        jLabel1.setText("Codigo");

        jLabel2.setText("Nombre");

        jLabel3.setText("Almacen");

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(5, 5, 5)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(jLabel3)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(codigo, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE)
                            .add(nombreMaterial, 0, 159, Short.MAX_VALUE)
                            .add(almacen, 0, 159, Short.MAX_VALUE)))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, submit))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(codigo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(nombreMaterial, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(4, 4, 4)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(almacen, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel3))
                        .add(18, 18, 18)
                        .add(submit))
                    .add(jLabel2)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void codigoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_codigoFocusLost
        if (codigo.getText().isEmpty()) {
            return;
        }
        manejadorDB db = new manejadorDB();
        Map<Integer, String[]> tempMap = db.getAtributosMateriales(Integer.parseInt(codigo.getText()));
        if (!tempMap.isEmpty()) {
            for (Map.Entry<Integer, String[]> dic : tempMap.entrySet()) {
                nombreMaterial.setSelectedItem(dic.getValue()[0]);
            }
        }
    }//GEN-LAST:event_codigoFocusLost

    private void submitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitActionPerformed
        // TODO add your handling code here:
        List<String[]> dataReport;
        manejadorDB mDB = new manejadorDB();
        Integer idAlmacen = Integer.parseInt(almacen.getSelectedItem().toString().split("-")[0]);
        Integer idMaterial = mDB.getMaterialID(nombreMaterial.getSelectedItem().toString());
        dataReport = mDB.getReportData(idAlmacen, idMaterial);
        imprimirReporte impri = new imprimirReporte(nombreMaterial.getSelectedItem().toString(),
                almacen.getSelectedItem().toString().split("-")[1]);
        impri.formatoImprimible(dataReport);
        try {
            impri.imprimir(new File("./tempImprimible.pdf"));
        } catch (Exception ioE) {
            System.out.println(ioE.getMessage());
        }


    }//GEN-LAST:event_submitActionPerformed

    private void nombreMaterialActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nombreMaterialActionPerformed
        // TODO add your handling code here:
        manejadorDB mDB = new manejadorDB();
        String data = mDB.getDataByName(nombreMaterial.getSelectedItem().toString());
        populateFielda(data);
    }//GEN-LAST:event_nombreMaterialActionPerformed
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox almacen;
    private javax.swing.JTextField codigo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JComboBox nombreMaterial;
    private javax.swing.JButton submit;
    // End of variables declaration//GEN-END:variables

    private void populateFielda(String data) {
        codigo.setText(data);
    }

    class manejadorDB extends DB {

        public manejadorDB() {
        }

        public Map<Integer, String> getNombreAlmacen() {
            Map<Integer, String> resultadoMap = new HashMap<Integer, String>();
            conectarDB();
            try {
                rs = stmt.executeQuery("select nombre,idAlmacen from Almacenes");
                while (rs.next()) {
                    resultadoMap.put(rs.getInt("idAlmacen"), rs.getString("nombre"));
                }
            } catch (Exception e) {
            } finally {
                desconectarDB();
                return resultadoMap;
            }
        }

        public List<String> getNombreMateriales() {
            List<String> resultadoList = new ArrayList<String>();
            conectarDB();
            try {
                rs = stmt.executeQuery("select nombre from Materiales");
                while (rs.next()) {
                    resultadoList.add(rs.getString("nombre"));
                }
            } catch (Exception e) {
            } finally {
                desconectarDB();
                return resultadoList;
            }
        }

        public Map<Integer, String[]> getAtributosMateriales(Integer numIdentificacion) {
            Map<Integer, String[]> resultadoMap = new HashMap<Integer, String[]>();
            conectarDB();
            try {
                rs = stmt.executeQuery("select idMaterial,nombre,unidad from "
                        + "Materiales where NoIdentificacion = '" + numIdentificacion + "'");
                String[] tempString = new String[2];
                while (rs.next()) {
                    tempString[0] = rs.getString("nombre");
                    tempString[1] = rs.getString("unidad");
                    resultadoMap.put(rs.getInt("idMaterial"), tempString);
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            } finally {
                desconectarDB();
                return resultadoMap;
            }
        }

        public List<String[]> getReportData(Integer idAlmacen, Integer idMaterial) {
            List<String[]> result = new ArrayList<String[]>();
            String query = "Select V.idVale as NoVale, V.Fecha as FechaVale, DV.Cantidad as "
                    + "CantidadMaterial, M.Unidad as UnidadMaterial, M.NoIdentificacion "
                    + "as CodigoMaterial, CONCAT(E.Nombre, \" \", E.Apellido) as NombreCompleto "
                    + "from Vales V, DetalleVale DV, Materiales M, Empleados E, "
                    + "Empleados A "
                    + "where V.idVale = DV.idVale and DV.idMaterial = "
                    + "M.idMaterial and V.Empleado = E.idEmpleado and "
                    + "A.idEmpleado = V.AutorizadoPor and "
                    + "DV.idMaterial = '" + idMaterial + "' "
                    + "and idAlmacen = '" + idAlmacen + "'";
            conectarDB();
            try {
                rs = stmt.executeQuery(query);
                ResultSetMetaData rsmd = rs.getMetaData();
                while (rs.next()) {
                    String[] row = new String[rsmd.getColumnCount()];
                    row[0] = rs.getString("NoVale");
                    row[1] = rs.getString("FechaVale");
                    row[2] = rs.getString("CantidadMaterial");
                    row[3] = rs.getString("UnidadMaterial");
                    row[4] = rs.getString("CodigoMaterial");
                    row[5] = rs.getString("NombreCompleto");
                    result.add(row);
                }
            } catch (Exception e) {
            } finally {
                desconectarDB();
                return result;
            }
        }

        public Integer getMaterialID(String nombre) {
            Integer result = 0;
            conectarDB();
            try {
                rs = stmt.executeQuery("Select idMaterial from Materiales where Nombre = '" + nombre + "'");
                while (rs.next()) {
                    result = rs.getInt("idMaterial");
                }
            } catch (Exception e) {
            } finally {
                desconectarDB();
                return result;
            }
        }

        private String getDataByName(String Nombre) {
            conectarDB();
            String result = null;
            try {
                rs = stmt.executeQuery("Select NoIdentificacion, Unidad from "
                        + "Materiales where Nombre ='" + Nombre + "'");
                while (rs.next()) {
                    result = rs.getString("NoIdentificacion");
                }
            } catch (Exception e) {
            } finally {
                desconectarDB();
                return result;
            }
        }
    }
}

class imprimirReporte extends Padre {

    private String nombreAlmacen, nombreMaterial;
    private String[] arr = {"Numero Vale", "Fecha Salida", "Cantidad Materia",
        "Unidad Material", "Codigo Material", "Nombre Empleado"};

    public imprimirReporte(String nombreAlmacen, String nombreMaterial) {
        this.nombreAlmacen = nombreAlmacen;
        this.nombreMaterial = nombreMaterial;
    }

    public void formatoImprimible(List<String[]> entradaList) {
        try {
            crearPDF();
            BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", false);
            HeaderFooter headerFooter = new HeaderFooter(new Phrase("", new Font(bf_helv)), true);
            documento.setFooter(headerFooter);
            documento.open();
            Image logo = Image.getInstance("./" + "/src/Interfaces/" + "EDENORTE.jpg");
            logo.setAlignment(logo.LEFT);
            documento.add(logo);
            Paragraph p = new Paragraph("Reporte de salidas de: " + nombreAlmacen + " en " + nombreMaterial);
            documento.add(p);
            Paragraph p1Paragraph = new Paragraph(" ");
            documento.add(p1Paragraph);
            PdfPTable table = new PdfPTable(6);
            for (String string : arr) {
                table.addCell(string);
            }
            for (String[] tempString : entradaList) {
                for (String string : tempString) {
                    table.addCell(string);
                }
            }
            documento.add(table);
        } catch (DocumentException de) {
            System.err.println(de.getMessage());
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
        } finally {
            cerrarPDF();
        }

    }
}

class comprobarDatos extends Thread {

    private JTextField codigo;
    private JComboBox nombre, almacen;
    private JButton submit;

    public comprobarDatos(JTextField codigo, JComboBox nombre, JComboBox almacen, JButton submit) {
        this.codigo = codigo;
        this.nombre = nombre;
        this.almacen = almacen;
        this.submit = submit;
    }

    @Override
    public void run() {
        checkFields();
    }

    public void checkFields() {
        while (true) {
            if ((codigo.getText().isEmpty() && nombre.getSelectedItem().toString().isEmpty()) || almacen.getSelectedItem().toString().isEmpty()) {
                submit.setEnabled(false);
            } else {
                submit.setEnabled(true);
            } /*else {
            submit.setEnabled(false);
            }*/
        }
    }
}
